package com.dyzx.hbb.modules.sms.service.impl;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.date.DateUnit;
import com.dyzx.hbb.modules.sms.service.SmsService;
import com.dyzx.hbb.aliyun.sms.utils.SmsClient;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SmsServiceImpl implements SmsService {
    @Autowired
     private SmsClient smsClient;
    Cache<String,String> fifoCache = CacheUtil.newFIFOCache(0);
    @Override
    public void sendVerificationCode(@NotBlank @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") String phoneNumber) {
        int vcode = smsClient.sendVerificationCode("vcode", phoneNumber);
        long l = DateUnit.MINUTE.getMillis() * 5;
        fifoCache.put(phoneNumber, String.valueOf(vcode),l);
    }

    @Override
    public boolean validateSmsCode(@NotBlank @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") String phone,
                                 @NotBlank @Pattern(regexp = "^\\d{6}$", message = "验证码格式不正确") String smsCode) {
        String code = fifoCache.get(phone);
        if(code == null) {
            return false;
        }
        boolean equals = code.equals(smsCode);
        if(equals){
            fifoCache.remove(phone);
        }
        return equals;
    }
    @Override
    public void sendNewPassword(@NotBlank @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") String phoneNumber,String password)  {

      smsClient.sendNewPassword("vcode", phoneNumber,password);
    }
}
